import React, { memo, useEffect, useRef, useState } from "react";

import { useDispatch, useSelector, shallowEqual } from "react-redux";

import { Slider } from "antd";

import { message } from "antd";

import { getSizeImage, formatDate, getPlaySong } from "@/utils/format-utils";

import {
  getSongDetailAction,
  changesequenceAction,
  changeCurrentIndexandSongAction,
  changeCurrentLyricIndexAction,
} from "../store/actionCreator";

import { PlaybarWrapper, Control, PlayInfo, Operator } from "./style";
import { useCallback } from "react";
import { NavLink } from "react-router-dom";
export default memo(function CLAppPlayerBar() {
  //state
  const [currentTime, setCurrentTime] = useState(0);

  const [progress, setProgress] = useState(0);
  //进度条改变
  const [isChange, setChange] = useState(0);
  //播放暂停
  const [isPlaying, setPlaying] = useState(false);
  //redux hooks

  //other hooks  28285910
  const dispatch = useDispatch();

  let { currentSong, sequence, lyricList, lyRiCIndex } = useSelector(
    (state) => ({
      currentSong: state.getIn(["palyer", "currentSong"]),
      sequence: state.getIn(["palyer", "sequence"]),
      lyricList: state.getIn(["palyer", "lyricList"]),
      lyRiCIndex: state.getIn(["palyer", "lyRiCIndex"]),
    }),
    shallowEqual
  );
  const audioRef = useRef();
  useEffect(() => {
    dispatch(getSongDetailAction(28285910));
  }, [dispatch]);

  useEffect(() => {
    audioRef.current.src = getPlaySong(currentSong.id);
    audioRef.current
      .play()
      .then((res) => {
        setPlaying(true);
      })
      .catch((err) => {
        setPlaying(false);
      });
  }, [currentSong]);
  //other handle
  //封面图
  const imgUrl = currentSong.al && currentSong.al.picUrl;
  //歌名&&歌手
  const singerName = currentSong.ar && currentSong.ar[0].name;

  const duration = currentSong.dt || 0;
  const showDuration = formatDate(duration, "mm:ss");
  const showCurrentTime = formatDate(currentTime, "mm:ss");
  //other function
  const playMusic = useCallback(() => {
    isPlaying ? audioRef.current.pause() : audioRef.current.play();
    setPlaying(!isPlaying);
  }, [isPlaying]);
  const timeUpdate = (e) => {
    const currentTime = e.target.currentTime;
    if (!isChange) {
      setCurrentTime(currentTime * 1000);
      setProgress(((currentTime * 1000) / duration) * 100);
    }

    //获取歌词
    let i = 0;
    for (; i < lyricList.length; i++) {
      const lyricItem = lyricList[i];
      if (currentTime * 1000 < lyricItem.time) {
        break;
      }
    }
    //如果歌词索引发生了改变 派发actionlyRiCIndex
    if (lyRiCIndex !== i - 1) {
      dispatch(changeCurrentLyricIndexAction(i - 1));
      message.open({
        content: lyricList[i - 1] && lyricList[i - 1].content,
        key: "lyric",
        duration: 0,
        className: "lyric-class",
      });
    }
  };
  //进度条拖动
  const sliderChange = useCallback(
    (value) => {
      // console.log("start:" + value);
      setChange(true);
      setCurrentTime((value / 100) * duration);
      setProgress(value);
    },
    [duration]
  );

  //进度条结束拖动
  const sliderAfterChange = useCallback(
    (value) => {
      // console.log("end:" + value);

      audioRef.current.currentTime = ((value / 100) * duration) / 1000;

      setCurrentTime(currentTime * 1000);
      setChange(false);
      //如果当前是暂停状态
      if (!isPlaying) {
        playMusic();
      }
    },
    [duration, currentTime, isPlaying, playMusic]
  );

  //切换播放方式
  const changeSequence = () => {
    //先从store获取 再修改
    let newSequence = sequence + 1;
    if (sequence >= 2) {
      newSequence = 0;
    }

    dispatch(changesequenceAction(newSequence));
  };
  //切歌
  const changeMusic = (tags) => {
    dispatch(changeCurrentIndexandSongAction(tags));
  };
  //歌曲播放结束
  const musicEnd = () => {
    //单曲循环
    if (sequence === 2) {
      audioRef.current.currentTime = 0;
      audioRef.current.play();
    } else {
      dispatch(changeCurrentIndexandSongAction(1));
    }
  };
  return (
    <PlaybarWrapper className="sprite_player">
      <div className="content wrap-v2">
        <Control isPlaying={isPlaying}>
          <button
            className="sprite_player prev"
            onClick={(e) => changeMusic(-1)}
          ></button>
          <button
            className="sprite_player play"
            onClick={(e) => playMusic()}
          ></button>
          <button
            className="sprite_player next"
            onClick={(e) => changeMusic(1)}
          ></button>
        </Control>
        <PlayInfo>
          <div className="image">
            <NavLink to="/discover/player">
              <img src={getSizeImage(imgUrl, 35)} alt="" />
            </NavLink>
          </div>
          <div className="info">
            <div className="song">
              <span className="song-name">{currentSong.name}</span>
              <a href="#/" className="singer-name">
                {singerName}
              </a>
            </div>
            <div className="progress">
              <Slider
                value={progress}
                onChange={sliderChange}
                onAfterChange={sliderAfterChange}
              />
              <div className="time">
                <span className="now-time">{showCurrentTime}</span>
                <span className="divider">/</span>
                <span className="duration">{showDuration}</span>
              </div>
            </div>
          </div>
        </PlayInfo>
        <Operator sequence={sequence}>
          <div className="left">
            <button className="sprite_player btn favor"></button>
            <button className="sprite_player btn share"></button>
          </div>
          <div className="right sprite_player">
            <button className="sprite_player btn volume"></button>
            <button
              className="sprite_player btn loop"
              onClick={(e) => changeSequence()}
            ></button>
            <button className="sprite_player btn playlist"></button>
          </div>
        </Operator>
        <audio ref={audioRef} onTimeUpdate={timeUpdate} onEnded={musicEnd} />
      </div>
    </PlaybarWrapper>
  );
});
